<template>
    <div class="container">
        <el-button type="primary" @click="exportExcelFn">导出Excel</el-button>
        <el-table
            :data="tableData"
            border
            style="width: auto; margin-top: 10px"
        >
            <el-table-column
                type="index"
                label="No."
                align="center"
                width="100"
            />
            <el-table-column prop="name" label="Name" align="center" />
            <el-table-column prop="age" label="Age" align="center" />
            <el-table-column label="Avatar" align="center">
                <template #default="{ row }">
                    <img :src="row.avatar" alt="" style="width: 160px" />
                </template>
            </el-table-column>
        </el-table>
    </div>
</template>
<script setup>
    import { ref } from "vue";

    import table2excel from "js-table2excel";

    // el-table的数据源
    const tableData = ref([
        {
            name: "AAAAA",
            age: 18,
            avatar: "https://element-plus.org/images/element-plus-logo.svg",
        },
        {
            name: "BBBBB",
            age: 20,
            avatar: "https://cdn-static-devbit.csdn.net/ai100/chat/imgs/icon-model-cover.png",
        },
    ]);

    // 导出按钮的回调函数
    function exportExcelFn() {
        const column = [
            {
                title: "名称",
                key: "name",
                type: "text",
                width: 300,
            },
            {
                title: "年龄",
                key: "age",
                type: "text",
                width: 300,
            },
            {
                title: "图片",
                key: "avatar",
                type: "image",
                width: 300,
            },
        ];
        table2excel(
            column,
            tableData.value,
            `用户列表${dateNum()}`,
            "表头：用户列表"
        );
    }

    // 获取日期 yyyy-MM-dd
    function dateNum() {
        let date = new Date();
        let year = date.getFullYear();
        let month =
            date.getMonth() + 1 > 9
                ? date.getMonth() + 1
                : "0" + (date.getMonth() + 1);
        let day = date.getDate() > 9 ? date.getDate() : "0" + date.getDate();
        return year + "-" + month + "-" + day;
    }
</script>
<style lang="scss" scoped></style>
